<!--
Module: NBIOT 配置页面
Author: 吴金根
date:2017/11/05
-->
<template>
  <div class="page-box">
    <Nav :indexs="0"  @clickit="gettoken"></Nav>
    <div class="realdata-wrap"  :style="addconfighigh">
        <div class="realdata-menus-wrap" >
       
            <div class="r-menus-btns">
                <div class="refesh-wrap">
                    <el-button type="primary" @click="goupdate" plain>更新</el-button>
                    <el-button type="success" @click="gorefresh" plain>重新加载</el-button>
                </div>
                <div class="searchcon">
                    <el-select v-model="keys" :multiple='false'  :value-key="keys.label"  :clearable="true" filterable remote placeholder="请输入位号" :remote-method="remoteMethod" :loading="loading" @change="handleSelect" @clear="nosearch">
                        <el-option v-for="item in SelectArray" :key="item.value" :label="item.label" :value="item.label" >
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="r-menus-list">
                <div class='sub-menu' id="left-menus" :style="MenusHeight">
                    <div class="jquery-accordion-menu hd-white el-app-menu" :style="MenusHeight">
                        <!-- <ul v-for="m1 in submenus" :key="m1.name" class="first-u">

                            <template :index="m1.name" v-if='m1.children && m1.children.length>0'>
                                <li>
                                    <a href='javascript:void(0)' class="first-a">

                                        {{m1.name}}
                                        <strong class="num-show" v-if="m1.children.length>0">({{m1.children.length}})</strong>
                                    </a>
                                      <ul class='submenu'>
                                    <template v-for="m2 in m1.children">
                                        <template v-if="m2.children == null || m2.children.length == 0">
                                          
                                                <li :key="m2">
                                                    <a href='javascript:void(0)' @click="loaddataclick(m1.name,m2,$event)" class="go-look">
                                                        <span>{{m2}}</span>
                                                    </a>
                                                </li>
                                           
                                        </template>
                                    </template>
                                     </ul>
                                </li>
                            </template>
                            <li :index="m1.name" v-else>
                                <a href='javascript:void(0)' class="go-look">
                                    <span>{{m1.name}}</span>
                                </a>
                            </li>
                        </ul> -->
                         <ul v-for="m1 in submenus" :key="m1.id">
                            <template :index="m1.id" v-if='m1.children && m1.children.length>0'>
                                <li>
                                    <a href='javascript:void(0)'>
                                        <i :class="m1.icon"></i>{{m1.name}}
                                         <strong class="num-show" v-if="m1.children.length>0">({{m1.children.length}})</strong>
                                    </a>
                                    <!-- <template v-for="m2 in m1.children">
                                        <template v-if="m2.children == null || m2.children.length == 0">
                                            <ul class='submenu' :key="m2.name">
                                                <li>
                                                    <a href='javascript:void(0)' class="go-looks">
                                                        <span>{{m2.name}}</span> <strong class="num-show" v-if="m2.children.length>0">({{m2.children.length}})</strong>
                                                    </a>
                                                </li>
                                            </ul>
                                        </template>
                                    </template> -->
                                    <ul class='submenu'>
                                        <template v-for="m2 in m1.children">
                                            <template v-if="m2.children && m2.children.length > 0">
                                                <template :index="m2.name">
                                                    <li :key="m2.id">
                                                        <a href='javascript:void(0)'>{{m2.name}}<strong class="num-show" v-if="m2.children.length>0">({{m2.children.length}})</strong></a>
                                                        <ul class='submenu'>
                                                            <template v-for="m3 in m2.children">
                                                                <li class="f-3" :daa-name="m2.name" :index="m3" :key="m3">
                                                                    <a :class='"my_"+m3' href='javascript:void(0)'@click="loaddataclick(m2.name,m3,$event)" class="go-look">
                                                                        <span>{{m3}}</span>
                                                                        <span class="p-name">{{m2.name}}</span>
                                                                    </a>
                                                                </li>
                                                            </template>
                                                        </ul>
                                                    </li>
                                                </template>
                                            </template>
                                        </template>
                                    </ul>
                                </li>
                            </template>
                            <li :index="m1.id" v-else>
                                <span>{{m1.name}}</span>
                            </li>
                        </ul>
                         <ul v-for="m1 in submenus2" :key="m1.name" class="first-u">

                            <template :index="m1.name" v-if='m1.children && m1.children.length>0'>
                                <li>
                                    <a href='javascript:void(0)' class="first-a">
                                        {{m1.name}}<strong style="color:red;margin-left:10px" v-if="m1.children.length>0">({{m1.children.length}})</strong>
                                    </a>
                                    <template v-for="m2 in m1.children">

                                        <template v-if="m1.children.length>0">
                                            <ul class='submenu' :key="m2" style="display:block">
                                                <li>
                                                    <a href='javascript:void(0)' class="go-look go-look2">
                                                        <span>{{m2}}</span>
                                                    </a>
                                                </li>
                                            </ul>
                                        </template>
                                    </template>
                                </li>
                            </template>
                            <li :index="m1.name" v-else>
                                <a href='javascript:void(0)' class="go-look">
                                    <span>{{m1.name}}</span>
                                </a>
                            </li>
                        </ul>
                    </div>

                </div>
            </div>
        </div>
        <div class="realdata-list-infos">
            <div class="lis--infos-table" :style="{'height':SystemTable+'px'}">
                <el-table  v-loading.body="loadingtable"  :style="{'height':SystemTable+'px'}" :max-height="SystemTable" border :data="listtablle" element-loading-text="加载中...">
                    <el-table-column prop="channel" label="名称" align="left">
                    </el-table-column>
                    <el-table-column prop="sn" label="位号" align="left">
                    </el-table-column>
                    <el-table-column prop="value" label="数值" align="left">
                    </el-table-column>
                    <el-table-column prop="dataTime" label="时间" align="left" :formatter="formatertime">
                    </el-table-column>
                    <el-table-column prop="updateTime" label="更新时间" align="center" :formatter="formatertime">
                    </el-table-column>
                </el-table>
            </div>
                <div class="tabs-box">
                    <div class="tabs-wrap" id="tabs-wrap">
                        <div class="tabs-content">
                            <div  class="tabs-content-s tabs-content-1" style="display:block"></div>
                            <div  class="tabs-content-s tabs-content-2">
                               <el-table  border :data="datastatus"  v-loading.body="loadingtable2"  :style="{'height':180+'px'}" :max-height="180" element-loading-text="加载中...">
                                    <el-table-column prop="name" label="驱动名称" align="left">
                                    </el-table-column>
                                    <el-table-column prop="port" label="端口" align="left">
                                    </el-table-column>
                                    <el-table-column prop="enable" label="状态" align="left" :formatter="formattertxt">
                                    </el-table-column>
                                    <el-table-column prop="state" label="启用" align="left" :formatter="formattertxt">
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div class="tabs-nav">
                            <span @click="opentxt($event,0)" class="on">数据监视</span>
                            <span @click="opentxt($event,1)">通信设备</span>
                        </div>
                    </div>
                </div>
        </div>

    </div>
  </div>
</template>
<script>
import Nav from "../components/nav.vue";
export default {
  components: {
    Nav
  },
  data() {
    return {
      datastatus: [], //驱动运行状态数据
      isupdata: true,
      index: 0,
      expand: false,
      name: "",
      loadingtable: true,
      loadingtable2: false,
      isshow: true, //展示日志开关
      tabPosition: "bottom",
      submenus:[{
                "name": "项目",
                "children":[],
            }],
      submenus2: [],
      token: "6f5ffdab-9dd9-4864-ab4a-658418e3ee56",
      listtablle: [], //列表数据
      isshowsubmenu: false,
      keys: "", //搜索关键词,
      loading: false,
      restaurants2: [], //搜索关键词总数
      list: [],
      states: [],
      SelectArray: [], //搜索展示数组
      issearch: false,
      firstinfos: {
        station: "",
        driveName: ""
      },
      startRun: null, //循环执行
      driveName: "", //参数名称
      station: "", //参数站号,
      isLoop: true //是否循环执行
    };
  },
  computed: {
    SystemTable: function() {
      let H = $(window).height() - 260 - 20 - 7 - 30;

      return H;
    },
    MenusHeight: function() {
      let style = { height: $(window).height() - 90 - 30 + "px" };
      return style;
    },
    addconfighigh: function() {
      let style = { height: $(window).height() - 52 + "px" };
      return style;
    }
  },
  methods: {
    opentxt($event, i) {
      let self = this;
      if (!$($event.currentTarget).hasClass("on")) {
        $($event.currentTarget)
          .siblings()
          .removeClass("on");
        $($event.currentTarget).addClass("on");
      }
      $("#tabs-wrap .tabs-content-s").css("display", "none");
      $("#tabs-wrap .tabs-content-s")
        .eq(i)
        .css("display", "block");
      self.getstatus();
    },
    formatertime(row, column, cellValue) {
      if (column.property === "dataTime") {
        return this.formatDateTime(row.dataTime);
      }
      if (column.property === "updateTime") {
        return this.formatDateTime(row.updateTime);
      }
    },
    loaddataclick(m1, m2, $event) {
      let self = this;
      // self.issearch=false;
      self.driveName = "";
      self.station = "";
      self.stopRun();
      if (
        !$($event.currentTarget)
          .find("span")
          .hasClass("ink")
      ) {
        $($event.currentTarget)
          .siblings()
          .removeClass("on");
        $($event.currentTarget).addClass("on");
      }
      $("#left-menus")
        .find(".go-look")
        .removeClass("current");
      $($event.currentTarget).addClass("current");
      self.loadingtable = true;

      self.station = m2;
      self.driveName = m1;

      self.loadData2(self.driveName, self.station);

      self.keys = [];
    },
    formatDateTime: function(inputTime) {
      var date = new Date(inputTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    },
    formattertxt(row, column, cellValue) {
      if (column.property === "enable") {
        if (row.enable) {
          return "正常";
        } else {
          return "关闭否";
        }
      }
      if (column.property === "state") {
        if (row.state) {
          return "启用";
        } else {
          return "停用";
        }
      }
    },
    goupdate() {
      let self = this;
      // self.loadData(); //获取左边菜单

      if (self.isupdata) {
        self.getnewdata();
      }
    },
    gorefresh() {
      this.$router.go(this.$router.currentRoute);
    },

    loadData() {
      let self = this;
      clearInterval(self.interval);
      jQuery.ajax({
        type: "POST",
        url: "/unitalk/v1.0/stations.json",
        contentType: "application/json",
        data: JSON.stringify({ Token: self.token }),
        dataType: "json",
        success: function(rep) {
          if (typeof rep == "string") {
            try {
              rep = JSON.parse(rep);
            } catch (err) {
              rep = {
                Code: 99999,
                Message: "数据初始化失败，请稍后再试！"
              };
            }
          }
          if (rep.Code == 0) {
            let data = rep.Response;
            let list = [];
            for (let key in data) {
              let obj = {};
              obj["name"] = key;
              obj["children"] = data[key];
              list.push(obj);
            }

            self.submenus[0].children =list
            self.loadingtable = false;
            self.leftnavload(); //执行左边菜单栏
            // 默认取第一条数据
            setTimeout(function() {
              if (self.submenus[0].children > 0) {
                if ( self.submenus[0].children.length > 0) {
                  self.driveName =  self.submenus[0].children[0].name;
                  self.station =  self.submenus[0].children[0].children[0];

                  self.loadData2(self.driveName, self.station);
                }
              }
            }, 100);

            // 默认取第一条数据
          }
        }
      });
    },
    getkhddata() {
      let self = this;

      jQuery.ajax({
        type: "POST",
        url: "/unitalk/v1.0/client.json",
        contentType: "application/json",
        data: JSON.stringify({ Token: self.token }),
        dataType: "json",
        success: function(rep) {
          if (typeof rep == "string") {
            try {
              rep = JSON.parse(rep);
            } catch (err) {
              rep = {
                Code: 99999,
                Message: "数据初始化失败，请稍后再试！"
              };
            }
          }
          if (rep.Code == 0) {
            // let list = [];

            // $.each(rep.Response,function(i,item){
            //   let obj = {};
            //   obj["name"] = item;
            //   obj["children"] = item;
            //   list.push(obj);
            // })
            self.submenus2 = [
              {
                name: "客户端",
                children: rep.Response
              }
            ];
            self.leftnavload(); //执行左边菜单栏
          }
        }
      });
    },
    loadData2(driveName, station) {
      let self = this;
      jQuery.ajax({
        type: "POST",
        url: "/unitalk/v1.0/station/sensors.json",
        contentType: "application/json",
        data: JSON.stringify({
          Token: self.token,

          driveName: driveName,
          station: station
        }),
        dataType: "json",
        success: function(rep) {
          if (typeof rep == "string") {
            try {
              rep = JSON.parse(rep);
            } catch (err) {
              rep = {
                Code: 99999,
                Message: "数据初始化失败，请稍后再试！"
              };
            }
          }
          if (rep.Code == 0) {
            // self.listtablle = [];

            self.listtablle = rep.Response; //dd
            setTimeout(function() {
              self.loadingtable = false;
              self.Loop();
            }, 1000);
          }
        }
      });
    },

    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;

        setTimeout(() => {
          this.loading = false;

          this.SelectArray = this.list.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.SelectArray = [];
      }
    },
    handleSelect(item) {
      let self = this;
      if (self.keys != "") {
      
        let name=$("body").find(".my_"+item).find(".p-name").html()
         self.driveName=name;
         self.station=item;
        self.loadData2(self.driveName, self.station);
    
      }
    },
    FirstloadTable() {
      //第一次加载表格显示第一个数据
      let self = this;
      // let txt = $.trim($("#left-menus").find("ul.first-u").eq(0).find(".first-a").text())
      // let txt2 = $.trim($("#left-menus").find("ul.first-u").eq(0).find(".go-look").eq(0).text())

      self.$nextTick(function() {
        setTimeout(function() {
          $("#left-menus")
            .find("ul.first-u")
            .find(".go-look")
            .eq(0)
            .click();
          $("#left-menus")
            .find("ul.first-u")
            .find(".go-look")
            .eq(0)
            .addClass("current");
        });
      }, 500);
    },
    GetSearchArray() {
      //获取搜索数组
      let self = this;

      if (self.submenus[0].children.length > 0) {
        let keyarr = [];
        $.each( self.submenus[0].children, function(i, item) {
          if (item.children.length > 0) {
            $.each(item.children, function(j, k) {
              let obj = {};
              obj["value"] = self.submenus[0].children[i].name;
              obj["label"] = k;
              keyarr.push(obj);
            });
          }
        });
        self.list = keyarr;
      }
    },
    leftnavload() {
      //加载左边菜单栏
      let self = this;
      self.GetSearchArray(); //获取搜索数组

      self.$nextTick(function() {
        //执行是否有滚动条
        let self = $(this.$el).find(".jquery-accordion-menu");
        self.jqueryAccordionMenu();

        $(self)
          .find(">ul>li")
          .each(function() {
            if (!$(this).hasClass("active")) {
              $(this)
                .click()
                .addClass("active");
            } else {
              $(this)
                .children(".submenu")
                .show();
            }
          });

        // $("#left-menus").slimScroll({
        //   height: $(window).height() - 90 - 30,
        //   size: "1px",
        //   opacity: 0
        // });

        setTimeout(function() {
          $("#left-menus")
            .find("ul.first-u")
            .find(".go-look")
            .eq(0)
            .addClass("current");
          $("#left-menus")
            .find("ul.first-u")
            .find(".go-look")
            .eq(0)
            .click();
        }, 500);

        //执行是否有滚动条
      });
    },
    gettoken(v) {
      //获取登录参数

      let self = this;
      self.token = v;
      /*------执行用户基本信息------*/
      self.getkhddata(); //执行客户端数据
      self.loadData(); //执行左边菜单栏数据
      self.getstatus(); //获取运行状态
    },
    getnewdata() {
      let self = this;
      jQuery.ajax({
        type: "POST",
        url: "/unitalk/v1.0/station/newstation.json",
        contentType: "application/json",
        data: JSON.stringify({
          Token: self.Token
        }),
        dataType: "json",
        success: function(rep) {
          if (typeof rep == "string") {
            try {
              rep = JSON.parse(rep);
            } catch (err) {
              rep = {
                Code: 99999,
                Message: "数据初始化失败，请稍后再试！"
              };
            }
          }
          if (rep.Code == 0) {
            self.isupdata = false;
            let data = rep.Response
            let list = [];
            for (let key in data) {
              let obj = {};
              obj["name"] = key;
              obj["children"] = data[key];
              list.push(obj);
            }

            if (list.length > 0) {
              $.each(list, function(j, k) {
                if (self.submenus.length > 0) {
                  $.each(self.submenus, function(i, item) {
                    if (k.name == item.name) {
                      self.submenus[i].children = self.submenus[
                        i
                      ].children.concat(list[j].children);
                    } else {
                      self.submenus.push(list[j]);
                    }
                  });
                } else {
                  self.submenus.push(list[j]);
                }
              });
            }
            setTimeout(function() {
              self.isupdata = true;
            }, 5000);
            self.leftnavload(); //执行左边菜单栏
          }
        }
      });
    },
    getstatus() {
      let self = this;

      self.datastatus = [];
      jQuery.ajax({
        type: "POST",
        url: "/unitalk/v1.0/device/runstate.json",
        contentType: "application/json",
        data: JSON.stringify({
          Token: self.Token
        }),
        dataType: "json",
        success: function(rep) {
          if (typeof rep == "string") {
            try {
              rep = JSON.parse(rep);
            } catch (err) {
              rep = {
                Code: 99999,
                Message: "数据初始化失败，请稍后再试！"
              };
            }
          }
          if (rep.Code == 0) {
            self.datastatus = rep.Response; //获取运行状态接口
          }
        }
      });
    },
    Loop: function() {
      //循环执行
      var self = this;
      self.startRun = setInterval(function() {
        self.loadData2(self.driveName, self.station);
      }, 60000);
    },
    stopRun: function() {
      //停止执行
      var self = this;
      clearInterval(self.startRun);
    },
    nosearch(item) {
      let self = this;
      self.loadData2(self.driveName, self.station);
       $("body").find(".go-look.current").removeClass("current")
      $("body").find(".my_"+self.station).addClass("current")
    }
  },
  mounted() {
    let self = this;
    self.gettoken(); //登录后在执行接口
    // setInterval(function() {
    //   self.loadData();

    //   self.goupdate();
    // }, 60000);
    //self.gettoken();
  },
  watch: {
    keys: function(key) {
      if (key == "") {
        let self = this;
        $("body")
          .find("#left-menus")
          .css("display", "block");

        //self.listtablle = [];
        self.loadingtable = true;
        //self.loadData();
      } else {
        $("body")
          .find("#left-menus")
          .css("display", "none");
        //self.loadData();
      }
    }
  }
};
</script>
